<template>
    <div class="container">
        <div class="header">
           <p>新增/修改账户</p>
           <!-- <el-button class="link" type="info">
                <router-link to="/accountList" style="color: #fff;">返回</router-link>
           </el-button> -->
       </div>
       <div class="main">
           <el-form :model="user" :rules="rules" ref="user" label-width="120px" class="">
             <el-form-item label="启用状态" prop="enable">
               <el-radio v-model="user.enable" label="y">启用</el-radio>
               <el-radio v-model="user.enable" label="n">关闭</el-radio>
             </el-form-item>
             <el-form-item label="账号" prop="userName">
               <el-input v-model="user.userName" placeholder="请输入登录名称"></el-input>
             </el-form-item>
              <el-form-item label="密码" prop="password">
                  <el-input v-model="user.password" placeholder="请输入密码"></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input v-model="user.confirmPassword" placeholder="请确认密码"></el-input>
              </el-form-item>
             <el-form-item label="角色" prop="roleId">
               <el-select v-model='user.roleId' placeholder='-请选择-'>
                 <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value"></el-option>
               </el-select>
             </el-form-item>
             <el-form-item label="头像" prop="avatar">
               <el-upload
                 class="avatar-uploader"
                 :action="upLoadUrl"
                 :show-file-list="false"
                 :before-upload="beforeAvatarUpload"
               >
                 <div v-if="user.avatarUrl">
                   <img :src="user.avatarUrl" class="avatar">
                 </div>
                 <i v-else class="el-icon-plus avatar-uploader-icon"></i>
               </el-upload>
             </el-form-item>
             <el-form-item label="备注" prop="remark">
               <el-input v-model="user.remark" placeholder="请输入备注"></el-input>
             </el-form-item>
              <el-form-item label="姓名" prop="trueName">
                  <el-input v-model="user.trueName" placeholder="请输入姓名"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="mobile">
                  <el-input v-model="user.mobile" placeholder="请输入手机号码"></el-input>
              </el-form-item>
             <el-form-item label="邮箱" prop="email">
               <el-input v-model="user.email" placeholder="请输入邮箱"></el-input>
             </el-form-item>
                <el-form-item>
                    <el-button type="primary"  @click="handleSave('user')">保存</el-button>
                    <el-button type="info" @click="backList">返回</el-button>
                </el-form-item>
            </el-form>
        </div>


    </div>
</template>

<script>
let CONSTANT = require('../../constant/constant.js');
let common = require("../../common.js");
export default {
    data() {
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            }
            else if (value !== this.user.password) {
                callback(new Error('两次输入密码不一致!'));
            }
            else {
                callback();
            }
        };
        var validateMobile = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入手机号码'));
            }
            else if (!(/^1[34578]\d{9}$/.test(value))) {
                callback(new Error('手机号码不合法!'));
            }
            else {
                callback();
            }
        };
      var validateEmail= (rule, value, callback) => {
        if (!(/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/.test(value))) {
          callback(new Error('邮箱格式不正确!'));
        } else{
          callback();
        }
      };
        return {
            id:'',
          upLoadUrl:"",
            user: {
              enable: "",
              userName:'',
              password:'',
              confirmPassword:'',
              trueName:'',
              mobile:'',
              roleName:'',
              roleId:'',
              avatar: "",
              remark: "",
              email: '',
            },
          roleList:[],
          pageUrlIndex:null,
            rules: {
                userName: [
                    { required: true, message: '请输入登录名称', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
              password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max:18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
                ],
              confirmPassword: [
                    { required: true, message: '请确认密码', trigger: 'blur' },
                    { validator: validatePass, trigger: 'blur' }
                ],
                trueName: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { validator: validateMobile, trigger: 'blur' }
                ],
                roleId:[
                    { required: true, message: '请选择角色类型', trigger: 'blur' },
                ],
              enable:[
                { required: true, message: '请选择启用状态', trigger: 'blur' },
              ],
              email:[
                { required: true, message: '请输入邮箱', trigger: 'blur' },
                { validator: validateEmail, trigger: 'blur' }
              ],
//              avatar:[
//                { required: true, message: '请选择邮箱', trigger: 'blur' },
//              ],
            },
        }
    },
    mounted() {
        this.id = this.$router.currentRoute.query.id;
        this.pageUrlIndex = this.$router.currentRoute.query.pageIndex;
        this.getRoleList();
        if(this.id){
           this.getUserById();
        }
    },
    methods: {
        backList:function(){
            // this.$router.go(-1);
            this.$router.push({name:'accountList',params:{'pageIndex':this.pageUrlIndex}});
        },
        getRoleList:function(){
            let url = CONSTANT.URL.SYSTEM.FINDAPPROLEBYPAGE;
            let dataForm = {
                pageIndex:1,
                pageSize:100
            }
            this.loading = true;
            common.post(url,dataForm,(res)=>{
                let data = res.data.bussData;
                data.map(function(item){
                    item["value"] = item.id;
                    item["label"] = item.roleName;
                })
                this.roleList = data;
                console.log(this.roleList)
            });
        },
        getUserById:function(){
           let url = CONSTANT.URL.SYSTEM.FINDADMINUSERDETAILBYUSERID;
           common.get(url,this.id,(res)=>{
                if(res.code == 200){
                    let data = res.data.bussData;
                    this.user= data;
                    this.user['avatarUrl'] = data.avatarUrl
                    // this.user.trueName = data.trueName;
                    // this.user.userName = data.userName;
                    // this.user.mobile = data.mobile;
                    // this.user.roleId = data.appRoleId;
                    // this.user.roleName = data.roleName;
                }
            })
        },
        getRoleId:function(event){
            this.user.roleId = event;
        },
        handleSave:function(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let url = CONSTANT.URL.SYSTEM.SAVEADMINUSER;
//                    let param;
//                    if(this.id){   // 编辑
//                        param = {
//                            userId:this.id,
//                            userName:this.user.userName,
//                            nickname:this.user.trueName,
//                            trueName:this.user.trueName,
//                            mobile:this.user.mobile,
//                            roleId:this.user.roleId
//                        };
//                    }
//                    else{
//                        param = {
//                            userName:this.user.userName,
//                            nickname:this.user.trueName,
//                            trueName:this.user.trueName,
//                            mobile:this.user.mobile,
//                            password:this.user.passwd,
//                            confirmPassword:this.user.confirmPasswd,
//                            roleId:this.user.roleId
//                        };
//                    }
                    common.post(url,this.user,(res)=>{
                        if(res.code == 200) {
                            this.$message({
                                type: 'success',
                                message: '保存账户信息成功！'
                            });
                            // this.$router.push("/accountList");
                            if(!!this.pageUrlIndex){
                                this.$router.push({name:'accountList',params:{'pageIndex':this.pageUrlIndex}});
                            }else{
                                this.$router.push("/accountList");
                            }
                        }
                        else{
                            this.$message({
                                type: 'warning',
                                message: res.data.errMsg
                            });
                        }
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        beforeAvatarUpload(index, file) {
          const isLt2M = file.size / 1024 / 1024 < 2;
          if (!isLt2M) {
            this.$message.error("上传头像图片大小不能超过 2MB!");
            return false;
          }
          let url =
            CONSTANT.URL.SYSTEM.ADMINUPLOADFILE +
            file.name.split(".")[1] +
            "?contentType=" +
            file.type;
          common.get(url, "", res => {
            let data = res.data.bussData;
            common.uploadFile(data.uploadUrl, file, file.type, res => {
              this.user.avatar = data.fileKey;
              this.user.avatarUrl = data.downloadUrl;
            });
          });
        },
    },

}
</script>
